package com.tech.freak.pyp;

import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.apps.analytics.GoogleAnalyticsTracker;
import com.tech.freak.pyp.data.SyncManager;
import com.tech.freak.pyp.model.CityRestriction;
import com.tech.freak.pyp.model.LicensePlate;

public class Pyp extends Activity{
	
	private static final String 		TAG = "Pico y Placa";
	
	private Context mContext;

	private TextView mPypLabel;
	private TextView mPypImage;
	
	private String mCity;
	private String mLicense;
	
	static final int DIALOG_CONFIRM_DB_UPDATE_ID = 0;
	static final int DIALOG_FIRST_RUN_ID = 1;
	//Menu
	private static final int UPDATE = Menu.FIRST;
	private static final int TOGGLE_ANALYTICS = Menu.FIRST+1;

	private Spinner mLicense_spinner;

	private Spinner mCity_spinner;
	
	private CityRestriction[] mCityRestrictions;
	
	private UpdateCompletedReceiver mUpdateReceiver;
	
	private ProgressDialog mProgressDialog;
		
	private Button mUpdate_btn;
	private Button mShow_data_btn;
	
	private static final String ANALYTICS_STATUS = "analytics";
	
	GoogleAnalyticsTracker tracker;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Request progress bar
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        
        setContentView(R.layout.main);
        Log.d(TAG, "onCreate");
        
        //Save context
        mContext = this;
        
        if(Utils.firstRun(mContext)){
        	Utils.preloadDB(mContext);
        	Utils.saveInfo(mContext, ANALYTICS_STATUS, Utils.TRUE);
        	showDialog(DIALOG_FIRST_RUN_ID);
        }
        
        //Start tracker
        tracker = GoogleAnalyticsTracker.getInstance();
        //tracker.start("UA-15859762-3", this);
        tracker.start("UA-15859762-3", 20, this);
        
        if(isAnalyticsEnabled()){
        	tracker.trackPageView("/PypScreen");
        }
        
        //Get update Button
        mUpdate_btn = (Button) findViewById(R.id.update_db_btn);
        mUpdate_btn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(isAnalyticsEnabled()){
		        	   tracker.trackEvent("Clicks","update_button_clicked","update_button", 0);
		        	   ////tracker.dispatch();
	        	}
				showDialog(DIALOG_CONFIRM_DB_UPDATE_ID);
				
			}
		});
        
        //Get show Button
        mShow_data_btn = (Button) findViewById(R.id.modify_db_btn);
        mShow_data_btn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(isAnalyticsEnabled()){
		        	   tracker.trackEvent("Clicks","show_button_clicked","show_button", 2);
		        	   ////tracker.dispatch();
	        	}
				startActivity(new Intent(getApplicationContext(), ShowPypData.class));
			}
		});
        
        //Create ad
        addAdvertisingView();
        
        //Get saved info
        mCity = Utils.getInfo(mContext, Utils.CITY);
        mLicense = Utils.getInfo(mContext, Utils.LICENSE);
        
		mPypLabel = (TextView) findViewById(R.id.pyp_label);
		mPypImage = (TextView) findViewById(R.id.pyp_icon);
		
        mLicense_spinner = (Spinner) findViewById(R.id.license_spinner);
        ArrayAdapter<CharSequence> license_adapter = ArrayAdapter.createFromResource(
                this, R.array.licenses, android.R.layout.simple_spinner_item);
        license_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mLicense_spinner.setAdapter(license_adapter);
        
        //Restore last value
        if(mLicense!=null && !mLicense.equalsIgnoreCase("")){
        	mLicense_spinner.setSelection(license_adapter.getPosition(mLicense));
        }
        
        mCity_spinner = (Spinner) findViewById(R.id.city_spinner);

        mUpdateReceiver = new UpdateCompletedReceiver();
        IntentFilter filter = new IntentFilter(Utils.UPDATE_SUCCESS);
        filter.addAction(Utils.UPDATE_ERROR);
        filter.addAction(Utils.UPDATE_ONGOING);
        registerReceiver(mUpdateReceiver, filter);
    }

	private void getInfoFromDB() {
		
		//Show progress bar
		setProgressBarIndeterminateVisibility(true);
		
		new AsyncTask<Void, Void, Void>() {

			@Override
			protected Void doInBackground(Void... params) {
				mCityRestrictions = Utils.getCityRestrictions(getContentResolver());
				return null;
			}

			/* (non-Javadoc)
			 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
			 */
			@Override
			protected void onPostExecute(Void result) {
				super.onPostExecute(result);
				
				//Hide progress bar
				setProgressBarIndeterminateVisibility(false);
				
				if(mCityRestrictions!=null){
			        CharSequence[] city_list = new CharSequence[mCityRestrictions.length];
			        
			        for (int i = 0; i < mCityRestrictions.length; i++) {
						city_list[i] = mCityRestrictions[i].getCity();
					}
			        
			        ArrayAdapter<CharSequence> city_adapter = new ArrayAdapter<CharSequence>(mContext, android.R.layout.simple_spinner_item, city_list);
			        city_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			        mCity_spinner.setAdapter(city_adapter);
			        
			        //Restore last value
			        if(!TextUtils.isEmpty(mCity)){
			        	mCity_spinner.setSelection(city_adapter.getPosition(mCity));
			        }
			        
			        setSpinnerListeners();
			        
			        displayPyP();
				}
				
			}
		}.execute();
		

		
	}

	protected void setSpinnerListeners() {
		mCity_spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int pos, long id) {
				mCity = parent.getItemAtPosition(pos).toString();
				Utils.saveInfo(mContext, Utils.CITY, mCity);
		        if(isAnalyticsEnabled()){
		        	tracker.trackPageView("/"+mCity.replace('\n', ' '));
		        	//tracker.dispatch();
		        }
				displayPyP();
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
		        //Put a default value
				mCity_spinner.setSelection(0);
		        displayPyP();
			}
		});
		
		mLicense_spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int pos, long id) {
				mLicense = parent.getItemAtPosition(pos).toString();
				Utils.saveInfo(mContext, Utils.LICENSE, mLicense);
				displayPyP();
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				mLicense_spinner.setSelection(0);
				displayPyP();
			}
		});
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		//Stop analytics tracker
		tracker.stop();
		
		//Unregister receiver
		unregisterReceiver(mUpdateReceiver);
		
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() {
		super.onPause();
	}


	/* (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		Log.d(TAG, "onResume");
		super.onResume();
		
        //Get all info from DB
        getInfoFromDB();
	}
	
	protected void displayPyP(){
		Log.d(TAG, "displayPyP()");
		LicensePlate pyp=null;
		if(mCityRestrictions!=null && !TextUtils.isEmpty(mCity) && !TextUtils.isEmpty(mLicense)){
			pyp = Utils.calculatePyP(this,mCityRestrictions, mCity, mLicense);
			if(pyp!=null){
				//Show correct view
				mPypImage.setBackgroundResource(pyp.getLicensePlate());
				String text = Utils.DAY_WEEK.format(new Date())+"\n";
				text=text.toUpperCase();
				text+=pyp.getRestrictions();
				text+="\n"+pyp.getCity().toUpperCase();
				mPypImage.setText(text.replace(',', '-'));
				if(pyp.isRestricted()){
					mPypLabel.setText(R.string.pypLabel);
					
				}else{
					mPypLabel.setText(R.string.no_pyplabel);
				}
			}
		}
	}
	
	private void addAdvertisingView() {

	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateDialog(int)
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog=null;
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		switch (id){
		case DIALOG_CONFIRM_DB_UPDATE_ID:
			
			builder.setMessage(R.string.dialog_confirm_update_db)
			       .setCancelable(false)
			       .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			        	   updateDb();
			           }
			       })
			       .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                dialog.cancel();
			           }
			       });
			dialog = builder.create();
			
			break;
		case DIALOG_FIRST_RUN_ID:
			builder.setMessage(R.string.dialog_first_run)
			.setPositiveButton(android.R.string.ok,new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
			dialog = builder.create();
			break;
		default:
			break;
		}
		
		return dialog;
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, UPDATE, Menu.NONE, R.string.menu_update_db).setIcon(R.drawable.ic_menu_refresh);
		menu.add(0, TOGGLE_ANALYTICS, Menu.NONE, R.string.menu_toggle_analytics).setIcon(R.drawable.ic_menu_block);
		return true;
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onMenuItemSelected(int, android.view.MenuItem)
	 */
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch(item.getItemId()) {
		case UPDATE:
			showDialog(DIALOG_CONFIRM_DB_UPDATE_ID);
			return true;
		case TOGGLE_ANALYTICS:
			if(isAnalyticsEnabled()){
	        	   tracker.trackEvent("Clicks","toggle_analytics_button_clicked","update_button_menu",1);       // Value
	        	   //tracker.dispatch();
			}
			toggleAnalytics();
			return true;
		default:
			return super.onMenuItemSelected(featureId, item);
		}
		
	}
	
	private void toggleAnalytics() {
		if(Utils.getInfo(mContext, ANALYTICS_STATUS).equalsIgnoreCase(Utils.TRUE)){
			Utils.saveInfo(mContext, ANALYTICS_STATUS, Utils.FALSE);
			Toast.makeText(mContext, getString(R.string.notification_analytics_disabled), Toast.LENGTH_LONG).show();
		}else{
			Utils.saveInfo(mContext, ANALYTICS_STATUS, Utils.TRUE);
			Toast.makeText(mContext, getString(R.string.notification_analytics_enabled), Toast.LENGTH_LONG).show();
		}
		
	}
	
	private boolean isAnalyticsEnabled(){
		if(Utils.getInfo(mContext, ANALYTICS_STATUS).equalsIgnoreCase(Utils.TRUE)){
			return true;
		}
		else return false;
	}

	private void updateDb(){
        
		//Call service
        startService(new Intent(mContext, SyncManager.class));
        sendBroadcast(new Intent(Utils.UPDATE_ONGOING));
	}
	
	private class UpdateCompletedReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
	        if (action.equalsIgnoreCase(Utils.UPDATE_SUCCESS)){
	        	if(mProgressDialog!=null){
	        		mProgressDialog.dismiss();
	        	}
	        	if(isAnalyticsEnabled()){
		        	   tracker.trackEvent("Update","update_finished_success","Success",0);
		        	   //tracker.dispatch();
	        	}
	        	Toast.makeText(context, getString(R.string.notification_update_success), Toast.LENGTH_LONG).show();
	        	
	        	//Update Info from DB
	        	getInfoFromDB();
	        }else if(action.equalsIgnoreCase(Utils.UPDATE_ERROR)){
	        	if(mProgressDialog!=null){
	        		mProgressDialog.dismiss();
	        	}
	        	if(isAnalyticsEnabled()){
		        	   tracker.trackEvent("Update","update_finished_error","Error",0);    
		        	   //tracker.dispatch();
	        	}
	        	Toast.makeText(context, getString(R.string.notification_update_error), Toast.LENGTH_LONG).show();
	        }else if(action.equalsIgnoreCase(Utils.UPDATE_ONGOING)){
	        	mProgressDialog = ProgressDialog.show(context, "", 
	        			getString(R.string.dialog_update_ongoing), 
	        			true, true);
	        	
	        }
			
		}
		
	}
}